package com.offcn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.mapper.*;
import com.offcn.pojo.*;
import com.offcn.service.SetmealService;
import com.offcn.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Resource
    private SetmealMapper setmealMapper;
    @Resource
    private SetmealCheckgroupMapper setmealCheckgroupMapper;

    @Override
    public PageResult queryAllSetmeal(QueryPageBean queryPageBean) {
        Page<Setmeal> page = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryPageBean.getQueryString())){
            queryWrapper.or().like("code",queryPageBean.getQueryString())
                    .or().like("name",queryPageBean.getQueryString())
                    .or().like("helpCode",queryPageBean.getQueryString());
        }
        Page<Setmeal> setmealPage = setmealMapper.selectPage(page, queryWrapper);
        PageResult pageResult = new PageResult(setmealPage.getTotal(), setmealPage.getRecords());
        return pageResult;
    }

    @Override
    public Result saveSetmeal(Setmeal setmeal, int[] checkgroupIds) {
        //添加setmeal表
        int rows = setmealMapper.insert(setmeal);
        //添加中间表,获取刚刚添加的setmeal的id

        if (checkgroupIds!=null && checkgroupIds.length>0){
            for (int checkgroupId : checkgroupIds) {
                SetmealCheckgroup setmealCheckgroup = new SetmealCheckgroup();
                setmealCheckgroup.setCheckgroupId(checkgroupId);
                setmealCheckgroup.setSetmealId(setmeal.getId());
                setmealCheckgroupMapper.insert(setmealCheckgroup);
            }
        }
        if (rows==1){
            return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
        }
        return new Result(false,MessageConstant.ADD_CHECKGROUP_FAIL);
    }

    @Override
    public SetmealAndCheckgroup getSetmealAndCheckgroup(int id) {
        Setmeal setmeal = setmealMapper.selectById(id);//当前这个套餐信息
        //这个套餐有什么检查组
        QueryWrapper<SetmealCheckgroup> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",id);
        List<SetmealCheckgroup> setmealCheckgroups = setmealCheckgroupMapper.selectList(queryWrapper);
        //请端要求的格式[1,2,3,4]
        List<Integer> ids=new ArrayList<>();
        for (SetmealCheckgroup setmealCheckgroup : setmealCheckgroups) {
            ids.add(setmealCheckgroup.getCheckgroupId());
        }
        return new SetmealAndCheckgroup(setmeal,ids);
    }

    @Override
    public Result deleteSetmeal(int id) {
        QueryWrapper<SetmealCheckgroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",id);
        setmealCheckgroupMapper.delete(queryWrapper);

        int row = setmealMapper.deleteById(id);
        if (row==1){
            return  new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
        }
        return  new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
    }

    @Override
    public boolean updateSetmealAndcheckgroup(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改setmeal表
        setmealMapper.updateById(setmeal);
        //修改中间表---先把旧的数据删除再添加一次
        QueryWrapper<SetmealCheckgroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",setmeal.getId());
        setmealCheckgroupMapper.delete(queryWrapper);
        //再添加一次
        if (checkgroupIds!=null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                SetmealCheckgroup setmealCheckgroup = new SetmealCheckgroup();
                setmealCheckgroup.setSetmealId(setmeal.getId());
                setmealCheckgroup.setCheckgroupId(checkgroupId);
                setmealCheckgroupMapper.insert(setmealCheckgroup);
            }
            return true;

        }
        return false;
    }

    @Override
    public List<SetmealEcharsVo> countSetmeal() {
        return setmealMapper.countSetmeal();
    }

    @Override
    public List<Setmeal> quertListSetmeal() {
        return setmealMapper.selectList(null);
    }

    @Resource
    private CheckgroupMapper checkgroupMapper;
    @Resource
    private CheckgroupCheckitemMapper checkgroupCheckitemMapper;
    @Resource
    private CheckitemMapper checkitemMapper;

    @Override
    public Setmeal getSetmealById(int id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        //查询这个套餐有什么检查组   查中间表
        QueryWrapper<SetmealCheckgroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",id);
        List<Checkgroup> checkgroupList = new ArrayList<>();//这个集合用于保存这个套餐有什么检查组
        //原则上这里一定能查到内容，因为添加套餐是一定要选检查组
        List<SetmealCheckgroup> setmealCheckgroupList = setmealCheckgroupMapper.selectList(queryWrapper);
        for (SetmealCheckgroup setmealCheckgroup : setmealCheckgroupList) {
            //查询检查组
            Checkgroup checkgroup = checkgroupMapper.selectById(setmealCheckgroup.getCheckgroupId());
            //查询这个检查组有什么检查项--查中间表
            QueryWrapper<CheckgroupCheckitem> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("checkgroup_id",checkgroup.getId());
            List<CheckgroupCheckitem> checkgroupCheckitemList = checkgroupCheckitemMapper.selectList(queryWrapper1);
            //查询检查项表
            List<Checkitem> checkitemList = new ArrayList<>(); //这个集合用于保存这个检查组有什么检查项
            for (CheckgroupCheckitem checkgroupCheckitem : checkgroupCheckitemList) {
                Checkitem checkitem = checkitemMapper.selectById(checkgroupCheckitem.getCheckitemId());
                checkitemList.add(checkitem);
            }

            checkgroupList.add(checkgroup);//把查到的检查组存到集合中
            checkgroup.setCheckitems(checkitemList);//把查到的检项组存到集合中
        }
        setmeal.setCheckgroups(checkgroupList);//吧刚刚查到的检查组集合存放到setmeal对象中
        return setmeal;
    }

    @Override
    public Setmeal getInfoById(int id) {
        Setmeal setmeal = setmealMapper.selectById(id);
        return setmeal;
    }

    @Resource
    private OrdersettingMapper ordersettingMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private OrderMapper orderMapper;


    @Override
    public Result setOrder(Map<String, String> map) {

// 1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行 预约
        String orderDate = map.get("orderDate");


        QueryWrapper<Ordersetting> ordersettingQueryWrapper=new QueryWrapper<>();
        ordersettingQueryWrapper.eq("orderDate",orderDate);
        List<Ordersetting> ordersettingList = ordersettingMapper.selectList(ordersettingQueryWrapper);
        if(ordersettingList==null || ordersettingList.size()==0){//没有查到  说明这个时间没有进行预约设置
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //已经进行预约设置
        // 2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        Ordersetting ordersetting = ordersettingList.get(0);
        if(ordersetting.getNumber()<=ordersetting.getReservations()){//已经约满
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //没有约满  可以进行预约
        //3检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        QueryWrapper<Member> memberQueryWrapper=new QueryWrapper<>();
        memberQueryWrapper.eq("phoneNumber",map.get("telephone"));
        List<Member> members = memberMapper.selectList(memberQueryWrapper);
        int orderMemberId=0;
        if(members==null || members.size()==0){//不是会员   不会出现【同一个用户在同一天预约了同一个套餐】的情况
            //自动注册     --添加一个会员
            Member inmember=new Member();
            inmember.setName(map.get("name"));
            inmember.setIdcard(map.get("idCard"));
            inmember.setPhonenumber(map.get("telephone"));
            inmember.setRegtime(LocalDateUtils.date2LocalDate(new Date()));
            if(map.get("sex").equals("1")){
                inmember.setSex("男");
            }else{
                inmember.setSex("女");
            }
            inmember.setPassword("123456");
            inmember.setBirthday(getBirthdayFromIdCard(map.get("idCard")));
            memberMapper.insert(inmember);
            orderMemberId=inmember.getId();
        }else{//是会员   同一个用户在同一天预约了同一个套餐
            Member member = members.get(0);
            QueryWrapper<Order> orderQueryWrapper=new QueryWrapper<>();
            orderQueryWrapper.eq("member_id",member.getId());
            orderQueryWrapper.eq("orderDate",orderDate);
            orderQueryWrapper.eq("setmeal_id",map.get("setmealId"));
            List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
            if(orderList!=null && orderList.size()>0){//查到了
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
            orderMemberId=member.getId();
        }
        //同一个用户在同一天没有预约同一个套餐-------进行预约
        LocalDate parse = LocalDate.parse(orderDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Integer setmealId = Integer.valueOf(map.get("setmealId"));

        Order order = new Order(0,orderMemberId,parse,"微信公众号预约","未到诊",setmealId);
        orderMapper.insert(order);
        //预约成功，更新当日的已预约人数
        ordersetting.setReservations(ordersetting.getReservations()+1);
        ordersettingMapper.updateById(ordersetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }

    private LocalDate getBirthdayFromIdCard(String idCard){
        String birthday =idCard.substring(6,10);
        birthday += "-"+idCard.substring(10,12);
        birthday += "-"+idCard.substring(12,14);
        LocalDate localDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return localDate;
    }
}
